package com.xfcode.ai.platform.ext;

import org.springframework.data.repository.init.ResourceReader;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.util.Base64;

public class FileReader {
    public static File getFile(String resourceName) {
        // 获取当前类的ClassLoader
        ClassLoader classLoader = ResourceReader.class.getClassLoader();
        // 通过ClassLoader获取资源的URL
        URL resource = classLoader.getResource(resourceName);

        // 检查资源是否存在
        if (resource == null) {
            System.out.println("资源文件不存在: " + resourceName);
            return null;
        }
        try {
            return  new File(resource.toURI());
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }
    public  static String getFileContent(String resourceName) {
        File f = getFile(resourceName);
        try {
            byte[] fileContent = Files.readAllBytes(f.toPath());
             return  new String(fileContent);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public  static String getBase64File(String resourceName) {
        File f=getFile(resourceName);
        try {
            byte[] fileContent = Files.readAllBytes(f.toPath());

            // 将字节数组转换为 Base64 编码
            String base64Encoded = Base64.getEncoder().encodeToString(fileContent);
            String mimeType = "image/png"; // 根据文件类型设置 MIME 类型
            // 构建 Data URI 格式
            return  "data:" + mimeType + ";base64," + base64Encoded;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
